<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="问卷编号" prop="surveysNo">
         <el-select v-model="queryParams.surveysNo" placeholder="请选择问卷编号" clearable size="small">
          <el-option  v-for="info1 in infoList" :key="info1.surveysNo" 
          :label="info1.surveysName" :value="info1.surveysNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleParentAdd"
          v-hasPermi="['surveys:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['surveys:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['surveys:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['surveys:question:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="问题编号" align="center" prop="questionNo" />
      <el-table-column label="标题" align="center" :show-overflow-tooltip="true"  prop="title" />
     
       <el-table-column label="父级编号" align="center" prop="questionParentId" > 
          <template slot-scope="scope">
             <el-tag v-if="scope.row.questionParentId==0">问题 </el-tag>
          <el-tag type="info" v-else>答案 {{scope.row.questionParentId}}</el-tag>
          </template>
       </el-table-column>
       <el-table-column label="问卷编号" align="center" prop="surveysNo" />
      <el-table-column label="问题主题" align="center" prop="questionMotifName" />
      
      <!-- <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" /> -->
      <el-table-column label="选择权" align="center" prop="options" :formatter="optionsFormat" />
      <el-table-column label="是否追加文字" align="center" prop="optionsSubjoin" :formatter="optionsSubjoinFormat"  />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="描述" align="center" :show-overflow-tooltip="true"  prop="description" />
      <!-- <el-table-column label="备注信息" align="center" prop="remarks" /> -->
      <el-table-column label="操作" align="left" class-name="small-padding" width="240px">
        <template slot-scope="scope">

          
            <el-button
            size="mini"
            type="text"
            icon="el-icon-plus" v-if="scope.row.type==0"
            @click="handleItemAdd(scope.row)"
            v-hasPermi="['surveys:question:edit']"
          >添加问题</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleParentUpdate(scope.row)" v-if="scope.row.type==0"
            v-hasPermi="['surveys:question:edit']"
          >修改</el-button>
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-if="scope.row.type==1"
            v-hasPermi="['surveys:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['surveys:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择问题" prop="questionParentId"> 
           <el-select v-model="form.questionParentId" placeholder="请选择问题" clearable size="small">
          <el-option  v-for="item in questionParentList" :key="item.questionNo" 
          :label="item.title" :value="item.questionNo" :title="item.surveysNo" /> 
        </el-select>
        </el-form-item>
        <el-form-item label="问题编号" prop="questionNo">
          <el-input v-model="form.questionNo" placeholder="请输入问题编号" />
        </el-form-item>
       
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="是否追加文字" prop="optionsSubjoin" v-if="form.type==1">
          <el-radio-group v-model="form.optionsSubjoin">
            <el-radio
              v-for="dict2 in optionsSubjoinOptions"
              :key="dict2.dictValue"
              :label="parseInt(dict2.dictValue)"
            >{{dict2.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description"  type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks"  type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

      <!-- 添加或修改题目信息对话框 -->
    <el-dialog :title="title" :visible.sync="parentOpen" width="500px" append-to-body>
      <el-form ref="parentform" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷编号" prop="surveysNo" >
           <el-select v-model="form.surveysNo" placeholder="请选择问卷编号" clearable size="small">
          <el-option  v-for="info in infoList" :key="info.surveysNo" 
          :label="info.surveysName" :value="info.surveysNo" />
        </el-select>
        </el-form-item>
        <el-form-item label="问题编号" prop="questionNo">
          <el-input v-model="form.questionNo" placeholder="请输入问题编号" />
        </el-form-item>
        <el-form-item label="问题主题" prop="questionMotifId" >
          <treeselect v-model="form.questionMotifId" :options="motifOptions" :normalizer="motifNormalizer" placeholder="请选择问题主题" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
      
        <el-form-item label="选择权">
          <el-radio-group v-model="form.options">
            <el-radio
              v-for="dict3 in optionsOptions"
              :key="dict3.dictValue"
              :label="parseInt(dict3.dictValue)"
            >{{dict3.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description"  type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks"  type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitParentForm">确 定</el-button>
        <el-button @click="cancelParent">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion, exportQuestion } from "@/api/surveys/question";
import { listInfo, getInfo} from "@/api/surveys/info";
import { listMotif, getMotif} from "@/api/surveys/motif";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Question",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 题目信息表格数据
      questionList: [],
      // 题目问题信息表格数据
      questionParentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      parentOpen:false,
      // 类型字典
      typeOptions: [],
      // 选择权字典
      optionsOptions: [],
      // 是否追加文字字典
      optionsSubjoinOptions: [],
      // 问卷基础信息表格数据
      infoList: [],
      // 题目主题树选项
      motifOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        surveysNo: undefined,
        questionParentId: undefined,
        type: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("surveys_question_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("surveys_options").then(response => {
      this.optionsOptions = response.data;
    });
     this.getDicts("common_yes_no").then(response => {
      this.optionsSubjoinOptions = response.data;
    });
    this.getInfoList();
  },
 watch:{
   'parentform.questionParentId':{
     handler(newName,oldName){
        console.log('change :' +newName);
        if(newName!=undefined){
        var actions = {};
	      Object.keys(this.questionParentList).map((questionNo) => {
	    	  if (this.questionParentList[questionNo].questionNo == ('' + newName)) {
			       actions=this.questionParentList[questionNo];
			      return false;
	  	    }
      	})
      	
        this.form.questionNo=newName+"1";
        this.form.surveysNo=actions.surveysNo;
        this.form.questionMotifId=actions.questionMotifId;
        this.form.options=actions.options;
        }
     },immediate:true
   }
 },
  methods: {
    /** 查询题目信息列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询问卷基础信息列表 */
    getInfoList() {
      listInfo().then(response => {
        this.infoList = response.rows;
      });
      listMotif().then(response => {
        this.motifOptions = [];
        const data = { questionMotifId: 0, questionMotifName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "questionMotifId", "parentId");
        this.motifOptions.push(data);
      });
      listQuestion({type:0}).then(response => {
        this.questionParentList = response.rows;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 选择权字典翻译
    optionsFormat(row, column) {
      return this.selectDictLabel(this.optionsOptions, row.options);
    },
    // 是否追加文字字典翻译
    optionsSubjoinFormat(row, column) {
      return this.selectDictLabel(this.optionsSubjoinOptions, row.optionsSubjoin);
    },
      /** 转换题目主题数据结构 */
    motifNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.questionMotifId,
        label: node.questionMotifName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
       this.resetForm("form");
    },
    cancelParent(){
      this.parentOpen = false;
      this.reset();
       this.resetForm("parentform");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        surveysNo: undefined,
        questionParentId: undefined,
        questionNo: undefined,
        questionMotifId: undefined,
        title: undefined,
        type: 0,
        options: 0,
        optionsSubjoin: 2,
        orderNum: 0,
        description: undefined,
        remarks: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
     
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleParentAdd() {
      this.reset();
      this.resetForm("parentform");
      this.parentOpen = true;
      this.form.type=0;
      this.title = "添加题目信息";
    },
    /** 新增子项按钮操作 */
    handleItemAdd(row) {
      this.reset();
       this.resetForm("form");
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        //this.form = response.data;
        listQuestion({type:0,surveysNo:response.data.surveysNo}).then(response => {
        this.questionParentList = response.rows;
        this.open = true;
        });
        
        this.title = "添加答案-"+response.data.questionNo;
        this.form.questionParentId=  response.data.questionNo;
        this.form.questionNo= response.data.questionNo+"1";
        
        this.form.type= 1;
        this.form.surveysNo= response.data.surveysNo;
        this.form.questionMotifId=response.data.questionMotifId;
        debugger
      });
      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(row.type==1){
      this.reset();
       this.resetForm("form");
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        listQuestion({type:0,surveysNo:response.data.surveysNo}).then(response => {
        this.questionParentList = response.rows;
        this.open = true;
        });
        this.form = response.data;
        this.title = "修改答案信息1-"+this.form.questionNo;
      });
      }else{
      this.handleParentUpdate(row);
      }
     
    },
     /** 修改问题按钮操作 */
    handleParentUpdate(row) {
      this.resetForm("parentform");
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data;
        this.parentOpen = true;
        this.title = "修改题目信息-1"+this.form.questionNo;
        debugger
      
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateQuestion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addQuestion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
        /** 提交问题按钮 */
    submitParentForm: function() {
      this.$refs["parentform"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateQuestion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.parentOpen = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addQuestion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.parentOpen = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除题目信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delQuestion(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有题目信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportQuestion(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>